﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Dao;
using Domain;
using eBayBus;
using eBayBus.Block;
using eBay.Service.Core.Soap;
using eBay.Service.Call;
using System.Collections;
using System.IO;
using Lib;

namespace StampApp
{
    public partial class AddPage : Form
    {
        public AddPage()
        {
            InitializeComponent();
            sel_site.SelectedIndex = 0;
            sel_template.SelectedIndex = 0;
            sel_ship.SelectedIndex = 0;
            sel_return.SelectedIndex = 0;
            sel_buyRequirement.SelectedIndex = 0;
            sel_checkout.SelectedIndex = 0;
            com_Sku.SelectedIndex = 0;

            Grid_Listinglib_Load();
            Grid_Active_Load();
            Grid_Fee_Load();
            BlockLoad();
            SkuLoad();
        }

        private void Grid_Listinglib_Load()
        {


            ChaEbayListingLibDao productDao = new ChaEbayListingLibDao();

            this.listinglib_grid.DataSource = new SortableBindingList<ChaEbayListingLib>(productDao.LoadAll());

            this.listinglib_grid.Sort(this.listinglib_grid.Columns["updatedate"], ListSortDirection.Descending);

            if (!this.listinglib_grid.Columns.Contains("index"))
            {

                this.listinglib_grid.Columns.Add("index", "id");
            }
            this.listinglib_grid.Columns["index"].DisplayIndex = 0;

            this.listinglib_grid.Columns["sku"].DisplayIndex = 1;
            this.listinglib_grid.Columns["title"].DisplayIndex = 2;
            this.listinglib_grid.Columns["startPrice"].DisplayIndex = 3;
            this.listinglib_grid.Columns["buyItNow"].DisplayIndex = 4;
            this.listinglib_grid.Columns["quantity"].DisplayIndex = 5;
            this.listinglib_grid.Columns["image"].DisplayIndex = 6;
            this.listinglib_grid.Columns["description"].DisplayIndex = 7;
            this.listinglib_grid.Columns["updateDate"].DisplayIndex = 8;
            this.listinglib_grid.Columns["createDate"].DisplayIndex = 9;

        }

        private void Grid_Fee_Load()
        {


            ChaEbayPostFeeDao PostFeeDao = new ChaEbayPostFeeDao();

            this.fee_grid.DataSource = new SortableBindingList<ChaEbayPostFee>(PostFeeDao.LoadAll());

            this.fee_grid.Sort(this.fee_grid.Columns["updatedate"], ListSortDirection.Descending);

            if (!this.fee_grid.Columns.Contains("index"))
            {
                this.fee_grid.Columns.Add("index", "id");
            }
            this.fee_grid.Columns["index"].DisplayIndex = 0;
        }

        private void Grid_Active_Load()
        {

            ChaEbayListingDao listingDao = new ChaEbayListingDao();

            this.activeListing_grid.DataSource = new SortableBindingList<ChaEbayListing>(listingDao.LoadAll());

            this.activeListing_grid.Sort(this.activeListing_grid.Columns["updatedate"], ListSortDirection.Descending);

            if (!this.activeListing_grid.Columns.Contains("index"))
            {

                this.activeListing_grid.Columns.Add("index", "id");
            }
            this.activeListing_grid.Columns["index"].DisplayIndex = 0;
            this.activeListing_grid.Columns["itemId"].DisplayIndex = 1;

            
        }

        private void BlockLoad()
        {


            Dictionary<string, string> siteBlocks = SiteBlock.GetAll();
            foreach (string iStr in siteBlocks.Keys)
            {
                ComboBoxItem xx = new ComboBoxItem();
                xx.Text = iStr;
                this.sel_site.Items.Add(xx);
            }

            Dictionary<string, string> shipBlocks = ShipBlock.GetAll();
            foreach (string iStr in shipBlocks.Keys)
            {
                ComboBoxItem xx = new ComboBoxItem();
                xx.Text = iStr;
                this.sel_ship.Items.Add(xx);
            }

            Dictionary<string, string> buyRequirementBlocks = BuyRequirementBlock.GetAll();
            foreach (string iStr in buyRequirementBlocks.Keys)
            {
                ComboBoxItem xx = new ComboBoxItem();
                xx.Text = iStr;
                this.sel_buyRequirement.Items.Add(xx);
            }

            Dictionary<string, string> returnBlocks = ReturnBlock.GetAll();
            foreach (string iStr in returnBlocks.Keys)
            {
                ComboBoxItem xx = new ComboBoxItem();
                xx.Text = iStr;
                this.sel_return.Items.Add(xx);
            }

            Dictionary<string, string> templateBlocks = TemplateBlock.GetAll();
            foreach (string iStr in templateBlocks.Keys)
            {
                ComboBoxItem xx = new ComboBoxItem();
                xx.Text = iStr;
                this.sel_template.Items.Add(xx);
            }

            Dictionary<string, string> checkoutBlocks = CheckoutBlock.GetAll();
            foreach (string iStr in checkoutBlocks.Keys)
            {
                ComboBoxItem xx = new ComboBoxItem();
                xx.Text = iStr;
                this.sel_checkout.Items.Add(xx);
            }
        }

        private void SkuLoad()
        {
            InvProductDao productDao = new InvProductDao();

            IList<InvProduct> products = productDao.LoadAll();

            Dictionary<string, string> siteBlocks = SiteBlock.GetAll();

            foreach (InvProduct iProduct in products)
            {
                ComboBoxItem xx = new ComboBoxItem();
                xx.Text = iProduct.sku;
                xx.Value = iProduct.productId;
                this.com_Sku.Items.Add(xx);
            }

        }

        private void button7_Click(object sender, EventArgs e)
        {

            if (txt_Title.Text.Length == 0
                || txt_StartPrice.Text.Length == 0
                || txt_Quantity.Text.Length == 0
                || txt_Image.Text.Length == 0
                || rTxt_Desc.Text.Length == 0
                || sel_buyRequirement.SelectedIndex == 0
                || sel_checkout.SelectedIndex == 0
                || sel_return.SelectedIndex == 0
                || sel_ship.SelectedIndex == 0
                || sel_site.SelectedIndex == 0
                || sel_template.SelectedIndex == 0
                || com_EbayAccount.SelectedItem == ""
                
                )
            {

                MessageBox.Show("please enter value!");

                return;
            }

            try
            {

                ChaEbayListingLibDao productDao = new ChaEbayListingLibDao();

                ChaEbayListingLib cp = new ChaEbayListingLib();
                cp.listingId = Guid.NewGuid();
                cp.buyItNow = Convert.ToDecimal(txt_BuyItNow.Text);
                cp.buyRequirementBlock = ((ComboBoxItem)this.sel_buyRequirement.SelectedItem).Text;
                cp.checkoutBlock = ((ComboBoxItem)this.sel_checkout.SelectedItem).Text;
                cp.createDate = DateTime.Now;
                cp.description = rTxt_Desc.Text;
                cp.image = txt_Image.Text;
                cp.quantity = Convert.ToInt32(txt_Quantity.Text);
                cp.returnBlock = ((ComboBoxItem)this.sel_return.SelectedItem).Text;
                cp.shippingBlock = ((ComboBoxItem)this.sel_ship.SelectedItem).Text;
                cp.siteBlock = ((ComboBoxItem)this.sel_site.SelectedItem).Text;
                cp.sku = ((ComboBoxItem)com_Sku.SelectedItem).Text;
                cp.startPrice = Convert.ToDecimal(txt_StartPrice.Text);
                cp.status = 0;
                cp.templateBlock = ((ComboBoxItem)this.sel_template.SelectedItem).Text;
                cp.title = txt_Title.Text;
                cp.updateDate = DateTime.Now;
                cp.ebayName = com_EbayAccount.SelectedItem.ToString();

                productDao.Save(cp);

                Grid_Listinglib_Load();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            foreach (DataGridViewRow row in listinglib_grid.Rows)
            {
                row.Cells[0].Value = row.Index + 1;
            }
        }

        private void but_Selected_Click(object sender, EventArgs e)
        {

            but_Selected.Enabled = false;

                foreach( DataGridViewRow iRow in  listinglib_grid.SelectedRows )
                {

                    Guid pid = new Guid(iRow.Cells["listingid"].Value.ToString());

                    ChaEbayListingLibDao productDao = new ChaEbayListingLibDao();
                    ChaEbayListingLib cp = productDao.Get(pid);

                    try
                    {

                        #region post item

                        ItemType itemType = new ItemType();


                        itemType.Quantity = cp.quantity;
                        itemType.SKU = cp.sku;
                        itemType.Title = cp.title;
                        itemType.StartPrice = new AmountType();
                        itemType.StartPrice.currencyID = CurrencyCodeType.USD;
                        itemType.StartPrice.Value = (double)cp.startPrice;

                        string[] images = System.Text.RegularExpressions.Regex.Split(cp.image, "@");
                        string imageAllStr = "";

                        foreach (string iImage in images)
                        {
                            imageAllStr += "<img src='" + iImage + "' border='0' alt='' > <br><br>";

                        }

                        itemType.PictureDetails = new PictureDetailsType();
                        itemType.PictureDetails.GalleryType = GalleryTypeCodeType.Gallery;
                        itemType.PictureDetails.GalleryURL = images[0];
                        itemType.PictureDetails.PictureSource = PictureSourceCodeType.Vendor;
                        itemType.PictureDetails.PictureSourceSpecified = true;
                        itemType.PictureDetails.PictureURL = new StringCollection(new string[] { images[0] });
                        itemType.PictureDetails.PhotoDisplay = PhotoDisplayCodeType.None;
                        itemType.PictureDetails.PhotoDisplaySpecified = true;

                        SiteBlock.SetBlock(cp.siteBlock, itemType, cp);
                        BuyRequirementBlock.SetBlock(cp.buyRequirementBlock, itemType);
                        CheckoutBlock.SetBlock(cp.checkoutBlock, itemType);
                        ReturnBlock.SetBlock(cp.returnBlock, itemType);
                        ShipBlock.SetBlock(cp.shippingBlock, itemType);
                        TemplateBlock.SetBlock(cp.templateBlock, itemType);
                        itemType.Description = itemType.Description.Replace("<!-- Type your description here -->",
                            "" + cp.description + "").Replace("<!-- Begin Photos -->",
                            imageAllStr).Replace("<!-- Type your title here -->", cp.title);


                        AddItemCall apicall = new AddItemCall(EbayConst.GetEbayContext(cp.ebayName));

                        apicall.ApiContext.Site = GetSite(cp.siteBlock);

                        //itemType.ListingEnhancement = new ListingEnhancementsCodeTypeCollection();
                        //itemType.ListingEnhancement.Add(ListingEnhancementsCodeType.BoldTitle);
                        
                        apicall.AddItem(itemType);


                        ChaEbayPostFeeDao PostFeeDao = new ChaEbayPostFeeDao();


                        foreach (FeeType iFee in apicall.ApiResponse.Fees)
                        {
                            if (iFee.Name != "ListingFee") continue;

                            ChaEbayPostFee newFee = new ChaEbayPostFee();

                            newFee.itemId = apicall.ApiResponse.ItemID;
                            newFee.name = iFee.Name;
                            newFee.fee = Convert.ToDecimal( iFee.Fee.Value );
                            newFee.currencyId = Convert.ToInt16( iFee.Fee.currencyID);
                            newFee.ebayFeeId = Guid.NewGuid();
                            newFee.postId = pid;
                            newFee.status = 0;
                            newFee.createDate = DateTime.Now;
                            newFee.updateDate = DateTime.Now;

                            if (cp.ebayName.Contains("testuser_"))
                            {
                                newFee.isSandbox = true;
                            }
                            else
                            {
                                newFee.isSandbox = false;                            
                            }

                            PostFeeDao.Save(newFee);
                        }


                        ChaEbayListing listing = new ChaEbayListing();
                        listing.buyItNow = cp.buyItNow;
                        listing.buyRequirementBlock = cp.buyRequirementBlock;
                        listing.checkoutBlock = cp.checkoutBlock;
                        listing.createDate = DateTime.Now;
                        listing.description = cp.description;
                        listing.ebayName = cp.ebayName;
                        listing.image = cp.image;
                        listing.isSandbox = cp.isSandbox;
                        listing.itemId = apicall.ApiResponse.ItemID;
                        listing.listingId = cp.listingId;
                        listing.quantity = cp.quantity;
                        listing.returnBlock = cp.returnBlock;
                        listing.shippingBlock = cp.shippingBlock;
                        listing.siteBlock = cp.siteBlock;
                        listing.sku = cp.sku;
                        listing.startPrice = cp.startPrice;
                        listing.status = 0;
                        listing.templateBlock = cp.templateBlock;
                        listing.title = cp.title;
                        listing.updateDate = DateTime.Now;

                        ChaEbayListingDao listingDao = new ChaEbayListingDao();

                        listingDao.Save(listing);



                        #endregion
                    }
                    catch (Exception ex)
                    {
                        FileHelp.WriteFile( "log.txt",ex.Message);
                    }
                }

                fee_grid_tab.SelectedIndex = 1;

                Grid_Active_Load();
                but_Selected.Enabled = true;


        }

        private void com_Sku_SelectedIndexChanged(object sender, EventArgs e)
        {


            if (com_Sku.SelectedItem.GetType() != typeof(ComboBoxItem)) return;

            ComboBoxItem sItem = (ComboBoxItem)com_Sku.SelectedItem;
            
            InvProductDao productDao = new InvProductDao();

            InvProduct product = productDao.Get(sItem.Value);
            txt_BuyItNow.Text = product.buyItNow.ToString();
            rTxt_Desc.Text = product.description;
            txt_Image.Text = product.image;
            txt_Quantity.Text = product.quantity.ToString();
            txt_StartPrice.Text = product.startPrice.ToString();
            txt_Title.Text = product.title;

        }

        private void dataGridView2_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            foreach (DataGridViewRow row in activeListing_grid.Rows)
            {
                row.Cells[0].Value = row.Index + 1;
            }
        }

        private void but_delete_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow iRow in listinglib_grid.SelectedRows)
            {
                ChaEbayListingLibDao productDao = new ChaEbayListingLibDao();


                Guid pid = new Guid(iRow.Cells["listingid"].Value.ToString());

                ChaEbayListingLib ll = productDao.Get(pid);
                productDao.Delete(ll);
            }

            Grid_Listinglib_Load();
        }

        private void com_EbayAccount_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (this.com_EbayAccount.SelectedItem.ToString().Contains("testuser_"))
            //{
            //    this.BackColor = Color.Gainsboro;
            //}
            //else
            //{
            //    this.BackColor = Color.Red;
            //}
        }

        string _sDirectory;
        private void but_import_Click(object sender, EventArgs e)
        {
            _sDirectory = System.IO.Directory.GetCurrentDirectory();

            this.openFileDialog1.ShowDialog();
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            //MessageBox.Show(this.openFileDialog1.FileName);
            StreamReader sr = new StreamReader(this.openFileDialog1.FileName, System.Text.Encoding.Default);

            System.IO.Directory.SetCurrentDirectory(_sDirectory);

            string error = "";
            string strLine = sr.ReadLine();
            while (strLine != null)
            {
                

                string[] ss = strLine.Split(',');

                if (ss[1].Length > 55) { error += ":" + ss[0];  }


                ChaEbayListingLib newProduct = new ChaEbayListingLib();

                newProduct.sku = ss[0];
                newProduct.title = ss[1];
                newProduct.buyItNow = Convert.ToDecimal(ss[2]);
                newProduct.quantity = Convert.ToInt32(ss[3]);
                newProduct.listingId = Guid.NewGuid();
                newProduct.startPrice = Convert.ToDecimal(ss[2]); ;
                newProduct.image = ss[4];
                newProduct.status = 0;
                newProduct.createDate = DateTime.Now;
                newProduct.updateDate = DateTime.Now;


                newProduct.description = ss[5];
                newProduct.ebayName = ss[6];
                newProduct.siteBlock = ss[7];
                newProduct.shippingBlock = ss[8];
                newProduct.checkoutBlock = ss[9];
                newProduct.returnBlock = ss[10];
                newProduct.buyRequirementBlock = ss[11];
                newProduct.templateBlock = ss[12];

                ChaEbayListingLibDao productDao = new ChaEbayListingLibDao();

                productDao.Save(newProduct);

                strLine = sr.ReadLine();
            }
            sr.Close();

            Grid_Listinglib_Load();

            MessageBox.Show(error);
        }

        private SiteCodeType GetSite(string blockName)
        { 
            string[] ssite = blockName.Split('_');

            switch (ssite[1])
            { 
                case "US":
                    return SiteCodeType.US;
                case "UK":
                    return SiteCodeType.UK;
                default:
                    return SiteCodeType.US;
            }
        
        }

        private void but_revise_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow iRow in activeListing_grid.SelectedRows)
            {

                string pid = iRow.Cells["itemid"].Value.ToString();

                ChaEbayListing elib = new ChaEbayListing();
                elib.itemId = pid;

                ChaEbayListingDao productDao = new ChaEbayListingDao();

                elib = productDao.Get(pid);

                this.txt_BuyItNow.Text = elib.buyItNow.ToString();
                this.txt_Image.Text = elib.image;
                this.txt_Quantity.Text = elib.quantity.ToString();
                this.txt_StartPrice.Text = elib.startPrice.ToString();
                this.txt_Title.Text = elib.title;
                this.rTxt_Desc.Text = elib.description;
                this.txt_itemid.Text = elib.itemId;

                foreach( object iComboBoxItem in sel_buyRequirement.Items)
                {
                    if ( iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.buyRequirementBlock)
                    {
                        sel_buyRequirement.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_checkout.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.checkoutBlock)
                    {
                        sel_checkout.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_return.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.returnBlock)
                    {
                        sel_return.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_ship.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.shippingBlock)
                    {
                        sel_ship.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_site.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.siteBlock)
                    {
                        sel_site.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_template.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.templateBlock)
                    {
                        sel_template.SelectedItem = iComboBoxItem;
                    }
                }

                foreach (object iComboBoxItem in com_Sku.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.sku)
                    {
                        com_Sku.SelectedItem = iComboBoxItem;
                    }
                }

            }
        }

        private void but_revise_post_Click(object sender, EventArgs e)
        {

            string pid = this.txt_itemid.Text;

            ChaEbayListing cp = new ChaEbayListing();
            cp.itemId = pid;

            ChaEbayListingDao productDao = new ChaEbayListingDao();

            cp = productDao.Get(pid);

            if (cp == null) return;

            #region revise item

            cp.buyItNow = Convert.ToDecimal(txt_BuyItNow.Text);
            cp.buyRequirementBlock = ((ComboBoxItem)this.sel_buyRequirement.SelectedItem).Text;
            cp.checkoutBlock = ((ComboBoxItem)this.sel_checkout.SelectedItem).Text;
            cp.createDate = DateTime.Now;
            cp.description = rTxt_Desc.Text;
            cp.image = txt_Image.Text;
            cp.quantity = Convert.ToInt32(txt_Quantity.Text);
            cp.returnBlock = ((ComboBoxItem)this.sel_return.SelectedItem).Text;
            cp.shippingBlock = ((ComboBoxItem)this.sel_ship.SelectedItem).Text;
            cp.siteBlock = ((ComboBoxItem)this.sel_site.SelectedItem).Text;
            cp.sku = ((ComboBoxItem)com_Sku.SelectedItem).Text;
            cp.startPrice = Convert.ToDecimal(txt_StartPrice.Text);
            cp.status = 0;
            cp.templateBlock = ((ComboBoxItem)this.sel_template.SelectedItem).Text;
            cp.title = txt_Title.Text;
            cp.updateDate = DateTime.Now;



            #region post item

            ItemType itemType = new ItemType();

            itemType.ItemID = cp.itemId;
            itemType.Quantity = cp.quantity;
            itemType.SKU = cp.sku;
            itemType.Title = cp.title;



            itemType.PictureDetails = new PictureDetailsType();
            itemType.PictureDetails.GalleryType = GalleryTypeCodeType.Gallery;
            itemType.PictureDetails.GalleryURL = cp.image;
            itemType.PictureDetails.PictureSource = PictureSourceCodeType.Vendor;
            itemType.PictureDetails.PictureSourceSpecified = true;
            itemType.PictureDetails.PictureURL = new StringCollection(new string[] { cp.image });
            itemType.PictureDetails.PhotoDisplay = PhotoDisplayCodeType.None;
            itemType.PictureDetails.PhotoDisplaySpecified = true;

            SiteBlock.SetBlock(cp.siteBlock, itemType, cp);
            BuyRequirementBlock.SetBlock(cp.buyRequirementBlock, itemType);
            CheckoutBlock.SetBlock(cp.checkoutBlock, itemType);
            ReturnBlock.SetBlock(cp.returnBlock, itemType);
            ShipBlock.SetBlock(cp.shippingBlock, itemType);
            TemplateBlock.SetBlock(cp.templateBlock, itemType);
            itemType.Description = itemType.Description.Replace("<!-- Type your description here -->",
                "<font face='Verdana' size='6'>" + cp.description + "</font>").Replace("<!-- Begin Photos -->",
                "<img src='" + cp.image + "' border='0' alt='Click here to Enlarge' >");


            ReviseItemCall apicall = new ReviseItemCall(EbayConst.GetEbayContext(cp.ebayName));

            apicall.ApiContext.Site = GetSite(cp.siteBlock);

            apicall.ReviseItem(itemType, new StringCollection(), false);

            productDao.Update(cp);



            #endregion


            Grid_Active_Load();

            #endregion
        }

        private void but_edit_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow iRow in listinglib_grid.SelectedRows)
            {

                string pid = iRow.Cells["listingid"].Value.ToString();

                ChaEbayListingLib elib = new ChaEbayListingLib();
                elib.listingId = new Guid( pid );

                ChaEbayListingLibDao productDao = new ChaEbayListingLibDao();

                elib = productDao.Get(elib.listingId);

                this.txt_BuyItNow.Text = elib.buyItNow.ToString();
                this.txt_Image.Text = elib.image;
                this.txt_Quantity.Text = elib.quantity.ToString();
                this.txt_StartPrice.Text = elib.startPrice.ToString();
                this.txt_Title.Text = elib.title;
                this.rTxt_Desc.Text = elib.description;
                this.txt_itemid.Text = elib.listingId.ToString();

                foreach (object iComboBoxItem in sel_buyRequirement.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.buyRequirementBlock)
                    {
                        sel_buyRequirement.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_checkout.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.checkoutBlock)
                    {
                        sel_checkout.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_return.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.returnBlock)
                    {
                        sel_return.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_ship.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.shippingBlock)
                    {
                        sel_ship.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_site.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.siteBlock)
                    {
                        sel_site.SelectedItem = iComboBoxItem;
                    }
                }
                foreach (object iComboBoxItem in sel_template.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.templateBlock)
                    {
                        sel_template.SelectedItem = iComboBoxItem;
                    }
                }

                foreach (object iComboBoxItem in com_Sku.Items)
                {
                    if (iComboBoxItem is ComboBoxItem && ((ComboBoxItem)iComboBoxItem).Text == elib.sku)
                    {
                        com_Sku.SelectedItem = iComboBoxItem;
                    }
                }

                foreach (object iComboBoxItem in com_EbayAccount.Items)
                {
                    if (iComboBoxItem.ToString()  == elib.ebayName)
                    {
                        com_EbayAccount.SelectedItem = iComboBoxItem;
                    }
                }

            }
        }

        private void but_save_Click(object sender, EventArgs e)
        {
            if (txt_Title.Text.Length == 0
                 || txt_StartPrice.Text.Length == 0
                 || txt_Quantity.Text.Length == 0
                 || txt_Image.Text.Length == 0
                 || rTxt_Desc.Text.Length == 0
                 || sel_buyRequirement.SelectedIndex == 0
                 || sel_checkout.SelectedIndex == 0
                 || sel_return.SelectedIndex == 0
                 || sel_ship.SelectedIndex == 0
                 || sel_site.SelectedIndex == 0
                 || sel_template.SelectedIndex == 0
                 || com_EbayAccount.SelectedItem == ""

                 )
            {

                MessageBox.Show("please enter value!");

                return;
            }

            try
            {

                ChaEbayListingLibDao productDao = new ChaEbayListingLibDao();

                ChaEbayListingLib cp = productDao.Get(new Guid(txt_itemid.Text));
                cp.buyItNow = Convert.ToDecimal(txt_BuyItNow.Text);
                cp.buyRequirementBlock = ((ComboBoxItem)this.sel_buyRequirement.SelectedItem).Text;
                cp.checkoutBlock = ((ComboBoxItem)this.sel_checkout.SelectedItem).Text;
                cp.createDate = DateTime.Now;
                cp.description = rTxt_Desc.Text;
                cp.image = txt_Image.Text;
                cp.quantity = Convert.ToInt32(txt_Quantity.Text);
                cp.returnBlock = ((ComboBoxItem)this.sel_return.SelectedItem).Text;
                cp.shippingBlock = ((ComboBoxItem)this.sel_ship.SelectedItem).Text;
                cp.siteBlock = ((ComboBoxItem)this.sel_site.SelectedItem).Text;
                cp.sku = ((ComboBoxItem)com_Sku.SelectedItem).Text;
                cp.startPrice = Convert.ToDecimal(txt_StartPrice.Text);
                cp.status = 0;
                cp.templateBlock = ((ComboBoxItem)this.sel_template.SelectedItem).Text;
                cp.title = txt_Title.Text;
                cp.updateDate = DateTime.Now;
                cp.ebayName = com_EbayAccount.SelectedItem.ToString();

                productDao.Update(cp);

                Grid_Listinglib_Load();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void but_Preview_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow iRow in listinglib_grid.SelectedRows)
                {

                    Guid pid = new Guid(iRow.Cells["listingid"].Value.ToString());

                    ChaEbayListingLibDao productDao = new ChaEbayListingLibDao();
                    ChaEbayListingLib cp = productDao.Get(pid);


                    #region post item

                    ItemType itemType = new ItemType();


                    itemType.Quantity = cp.quantity;
                    itemType.SKU = cp.sku;
                    itemType.Title = cp.title;
                    itemType.StartPrice = new AmountType();
                    itemType.StartPrice.currencyID = CurrencyCodeType.USD;
                    itemType.StartPrice.Value = (double)cp.startPrice;

                    string[] images = System.Text.RegularExpressions.Regex.Split(cp.image, "@");
                    string imageAllStr = "";

                    foreach (string iImage in images)
                    {
                        imageAllStr += "<img src='" + iImage + "' border='0' alt='' > <br><br>";

                    }

                    itemType.PictureDetails = new PictureDetailsType();
                    itemType.PictureDetails.GalleryType = GalleryTypeCodeType.Gallery;
                    itemType.PictureDetails.GalleryURL = images[0];
                    itemType.PictureDetails.PictureSource = PictureSourceCodeType.Vendor;
                    itemType.PictureDetails.PictureSourceSpecified = true;
                    itemType.PictureDetails.PictureURL = new StringCollection(new string[] { images[0] });
                    itemType.PictureDetails.PhotoDisplay = PhotoDisplayCodeType.None;
                    itemType.PictureDetails.PhotoDisplaySpecified = true;

                    SiteBlock.SetBlock(cp.siteBlock, itemType, cp);
                    BuyRequirementBlock.SetBlock(cp.buyRequirementBlock, itemType);
                    CheckoutBlock.SetBlock(cp.checkoutBlock, itemType);
                    ReturnBlock.SetBlock(cp.returnBlock, itemType);
                    ShipBlock.SetBlock(cp.shippingBlock, itemType);
                    TemplateBlock.SetBlock(cp.templateBlock, itemType);
                    itemType.Description = itemType.Description.Replace("<!-- Type your description here -->",
                        "" + cp.description + "").Replace("<!-- Begin Photos -->",
                        imageAllStr).Replace("<!-- Type your title here -->", cp.title);


                    VerifyAddItemCall apicall = new VerifyAddItemCall(EbayConst.GetEbayContext(cp.ebayName));

                    apicall.ApiContext.Site = GetSite(cp.siteBlock);

                    FeeTypeCollection fees = apicall.VerifyAddItem(itemType);

                    string feeStr = "";

                    foreach (FeeType iFee in fees)
                    {
                        if (iFee.Fee.Value > 0)
                        {
                            feeStr += "   " + iFee.Name + ":" + iFee.Fee.Value;
                        }
                    }

                    MessageBox.Show(feeStr);

                    #endregion

                }

                fee_grid_tab.SelectedIndex = 1;

                Grid_Active_Load();

            }
            catch (Exception ex)
            {
                ;
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

            for (int i = 0; i < this.listinglib_grid.Rows.Count; i++ )
            {
                if (this.listinglib_grid.Rows[i].Cells["ebayname"].Value != null && !this.listinglib_grid.Rows[i].Cells["ebayname"].Value.ToString().Contains("testuser_"))
                {

                    this.listinglib_grid.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.Red;
                }


                
            }
        }

        private void but_end_Click(object sender, EventArgs e)
        {
            if (com_EbayAccount.SelectedItem == null) return;

            but_end.Enabled = false;

            EndItemCall apicall = new EndItemCall(EbayConst.GetEbayContext(com_EbayAccount.SelectedItem.ToString()));

            ChaEbayListingDao listingDao = new ChaEbayListingDao();

            foreach (DataGridViewRow iRow in activeListing_grid.SelectedRows)
            {
                ChaEbayListingLibDao productDao = new ChaEbayListingLibDao();
                ChaEbayListing activelisting = new ChaEbayListing();

                activelisting.itemId = iRow.Cells["itemid"].Value.ToString();

                try
                {
                    apicall.EndItem(activelisting.itemId, EndReasonCodeType.NotAvailable);
                }
                catch (Exception ex)
                { }


                listingDao.Delete(activelisting);

            }

            Grid_Active_Load();

            but_end.Enabled = true;

        }

        private void fee_grid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            foreach (DataGridViewRow row in fee_grid.Rows)
            {
                row.Cells[0].Value = row.Index + 1;
            }
        }

        private void fee_grid_tab_Selected(object sender, TabControlEventArgs e)
        {
            Grid_Fee_Load();

        }

        private void but_post_Product_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("正式 提交 到eBay!","post",MessageBoxButtons.OKCancel) != DialogResult.OK) return;

            MessageBox.Show("正式!");
        }


    }
}
